package resultx

import (
	"fmt"
	"net/http"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/rest/httpx"
	"google.golang.org/grpc/status"
)

//http返回
func HttpResult(r *http.Request, w http.ResponseWriter, resp any, err error) {
	if err == nil {
		//成功返回
		s := Success(resp)
		httpx.WriteJsonCtx(r.Context(), w, http.StatusOK, s)
	} else {
		//错误返回
		errCode := SERVER_COMMON_ERROR
		errMsg := "服务器开小差啦，稍后再来试一试"

		causeErr := errors.Cause(err)           //err类型
		if e, ok := causeErr.(*CodeError); ok { //自定义错误类型
			//自定义CodeError
			errCode = e.GetErrCode()
			errMsg = e.GetErrMsg()
		} else {
			if gStatus, ok := status.FromError(causeErr); ok { //grpc err错误
				grpcCode := uint32(gStatus.Code())
				if IsCodeErr(grpcCode) { //区分自定义错误跟系统底层、db等错误，底层、db错误不能返回给前端
					errCode = grpcCode
					errMsg = gStatus.Message()
				}
			}
		}

		w.Header().Set("x-class", "com.djx.SystemException")
		httpx.WriteJsonCtx(r.Context(), w, http.StatusBadRequest, Error(errCode, errMsg))
	}
}

//授权的http方法
func AuthHttpResult(r *http.Request, w http.ResponseWriter, resp any, err error) {
	if err == nil {
		//成功返回
		s := Success(resp)
		httpx.WriteJsonCtx(r.Context(), w, http.StatusOK, s)
	} else {
		//错误返回
		errCode := SERVER_COMMON_ERROR
		errMsg := "服务器开小差啦，稍后再来试一试"

		causeErr := errors.Cause(err)           //err类型
		if e, ok := causeErr.(*CodeError); ok { //自定义错误类型
			//自定义CodeError
			errCode = e.GetErrCode()
			errMsg = e.GetErrMsg()
		} else {
			if gStatus, ok := status.FromError(causeErr); ok { //grpc err错误
				grpcCode := uint32(gStatus.Code())
				if IsCodeErr(grpcCode) { //区分自定义错误跟系统底层、db等错误，底层、db错误不能返回给前端
					errCode = grpcCode
					errMsg = gStatus.Message()
				}
			}
		}

		httpx.WriteJsonCtx(r.Context(), w, http.StatusUnauthorized, Error(errCode, errMsg))
	}
}

//http 参数错误返回
func ParamErrorResult(r *http.Request, w http.ResponseWriter, err error) {
	errMsg := fmt.Sprintf("%s, %s", MapErrMsg(REUQEST_PARAM_ERROR), err.Error())
	httpx.WriteJsonCtx(r.Context(), w, http.StatusBadRequest, Error(REUQEST_PARAM_ERROR, errMsg))
}
